package cn.hhchat.wp.service;

import cn.hhchat.kit.file.FileUtil;
import cn.hhchat.wp.config.SystemProperties;
import cn.hhchat.wp.dto.msg.ResultEnum;
import cn.hhchat.wp.entity.AttachmentEntity;
import cn.hhchat.wp.exception.FileCreateFailedException;
import cn.hhchat.wp.repository.AttachmentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Created this one by HMH on 2017/10/23.
 */
@Service
public class AttachmentService {

    public AttachmentEntity getById(long id) {
        return attachmentRepository.findOne(id);
    }


    @Autowired
    private SystemProperties sysConfig;

    public AttachmentEntity save(MultipartFile multipartFile){
        String rootDir = sysConfig.getResource().getDisRoot();
        String originFileName = multipartFile.getOriginalFilename();
        try {
            File fileToSave = FileUtil.createFileWithUUID(rootDir, originFileName);
            multipartFile.transferTo(fileToSave);
            AttachmentEntity attachmentEntity = new AttachmentEntity();
            attachmentEntity.setFileName(originFileName);
            attachmentEntity.setFilePath(fileToSave.getPath());
            attachmentEntity.setFileUrl(fileToSave.getName());
            return save(attachmentEntity);
        } catch (Exception e) {
            throw new FileCreateFailedException(e, ResultEnum.FileSystemError,"文件存储失败");
        }
    }

    public AttachmentEntity save(AttachmentEntity attachment) {
        return attachmentRepository.save(attachment);
    }

    @Autowired
    private AttachmentRepository attachmentRepository;

}
